package com.example.rubbish.Fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.example.rubbish.Adapter.ViewPagerAdapter;
import com.example.rubbish.R;
import com.example.rubbish.ResultActivity;
import com.example.rubbish.SearchActivity;
import com.example.rubbish.Utils.Base64Utils;

import java.util.ArrayList;
import java.util.List;


public class HomeFragment extends Fragment {
    private static final int WASTE_HAZARDOUS=R.drawable.hazardous_waste;
    private static final int WASTE_KITCHEN=R.drawable.kitchen_waste;
    private static final int WASTE_OTHER=R.drawable.other_waste;
    private static final int WASTE_RECYCLABLE=R.drawable.recyclable_waste;

    private View root;
    private Button searchIcon;

    private String result_bitmap;
    private Button button_photo;
    private ActivityResultLauncher<String> requestPermissionLauncher;
    private ActivityResultLauncher cameraLauncher;



    private ViewPager2 viewPager2;
    private int lastPosition;
    private List<Integer> imagesIds = new ArrayList<>();
    private LinearLayout indicatorContainer;
    private Handler mHandler = new Handler(Looper.getMainLooper());

    //Fragment注册活动回调启动器 要在onCreate 或 onAttach
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //授权启动器
        requestPermissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), new ActivityResultCallback<Boolean>() {
            @Override
            public void onActivityResult(Boolean result) {
                if(result){
                    takePhoto();
                }else {//仍拒绝
                    Toast.makeText(getContext(), "授权失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
        //相机
        cameraLauncher= registerForActivityResult(new ActivityResultContracts.TakePicturePreview(), new ActivityResultCallback<Bitmap>() {
            @Override
            public void onActivityResult(Bitmap result) {
                //按了取消拍照，返回result==null
                if(result!=null){
                    //bitmapQuality:压缩到x%，100：不压缩
                    result_bitmap = Base64Utils.bitmapToBase64(result,40);
                    Log.i("photo", "HERE:"+result_bitmap);
                    Intent intent = new Intent(getContext(), ResultActivity.class);
                    intent.putExtra("searchContent",result_bitmap);
                    intent.putExtra("searchType",1);
                    startActivity(intent);

                }

            }
        });

    }

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        root = inflater.inflate(R.layout.fragment_home, container,false);
        searchIcon = root.findViewById(R.id.searchIcon);
        button_photo= root.findViewById(R.id.picture_recognition);


        viewPager2=root.findViewById(R.id.viewpager2);
        indicatorContainer = root.findViewById(R.id.container_indicator);

        initImagesIds();
        initIndicatorDots();

        ViewPagerAdapter viewPagerAdapter= new ViewPagerAdapter(imagesIds);
        viewPager2.setAdapter(viewPagerAdapter);
        //初始在500，可以一开始就往前滑动
        viewPager2.setCurrentItem(500);
        lastPosition=500;

        return root;
    }

    private void initIndicatorDots() {

        for(int i=0 ;i<imagesIds.size();i++){
            ImageView dotView = new ImageView(getContext());
            if(i==0) {
                dotView.setImageResource(R.drawable.dot_white);
            }else{
                dotView.setImageResource(R.drawable.dot_drak);
            }

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.setMarginEnd(4);
            dotView.setLayoutParams(layoutParams);

            indicatorContainer.addView(dotView);
        }
    }

    private void initImagesIds() {
        imagesIds.add(WASTE_HAZARDOUS);
        imagesIds.add(WASTE_KITCHEN);
        imagesIds.add(WASTE_OTHER);
        imagesIds.add(WASTE_RECYCLABLE);
    }



    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        searchIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
            }
        });

        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                //改变dot
                int current = position % 4 ;
                int last = lastPosition % 4;
                indicatorContainer.getChildAt(current).setBackgroundResource(R.drawable.dot_white);
                indicatorContainer.getChildAt(last).setBackgroundResource(R.drawable.dot_drak);
                lastPosition=position;

            }
        });


        button_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //是否已授权相机
                if( ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){

                    //动态申请
                    requestPermissionLauncher.launch(Manifest.permission.CAMERA);

                }else {//已授权
                    takePhoto();
                }

            }
        });



    }//onViewCreated

    private void takePhoto() {
        cameraLauncher.launch(null);

    }

    @Override
    public void onResume() {
        super.onResume();
        mHandler.postDelayed(runnable, 5000);
    }

    @Override
    public void onPause() {
        super.onPause();
        mHandler.removeCallbacks(runnable);
    }
    private final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            int currentPosition = viewPager2.getCurrentItem();
            currentPosition++;
            viewPager2.setCurrentItem(currentPosition, true);
            mHandler.postDelayed(runnable, 5000);
        }
    };

}